<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0,user-scalable=no,minimal-ui">
        <title>馅饼研究所</title>
        <link rel="icon" href="../images/favico.ico">
        <!--不同屏幕尺寸根字体设置-->
        <script src="../js/base.js"></script>
        <!--element-ui的样式-->
        <link rel="stylesheet" href="../../backend/plugins/element-ui/index.css" />
        <!--引入vant样式-->
        <link rel="stylesheet" href="../styles/vant.min.css"/>
        <!-- 引入样式  -->
        <link rel="stylesheet" href="../styles/index.css" />
        <!--本页面内容的样式-->
        <link rel="stylesheet" href="../styles/add-order.css" />
    </head>
    <body>
        <div id="add_order" class="app">
            <div class="divHead">
                <div class="divTitle">
                    <i class="el-icon-arrow-left" @click="goBack"></i>馅饼研究所
                </div>
            </div>
            <div class="divContent">
                <div class="divAddress">
                    <div @click="toAddressPage">                    
                        <div class="address">{{address.detail}}</div>
                        <div class="name">
                            <span>{{address.consignee}}{{address.sex === '1' ? '先生':'女士'}}</span>
                            <span>{{address.phone}}</span>
                        </div>
                        <i class="el-icon-arrow-right"></i>
                    </div>
                    <div class="divSplit"></div>
                    <div class="divFinishTime">预计{{finishTime}}送达</div>
                </div>
                <div class="order">
                    <div class="title">订单明细</div>
                    <div class="divSplit"></div>
                    <div class="itemList">
                        <div class="item" v-for="(item,index) in cartData" :key="index">
                            <el-image :src="imgPathConvert(item.image)">
                                <div slot="error" class="image-slot">
                                    <img src="../images/noImg.png"/>
                                </div>
                            </el-image>
                            <div class="desc">
                                <div class="name">{{item.name}}</div>
                                <div class="numPrice">
                                    <span class="num">x{{item.number}}</span>
                                    <div class="price">
                                        <span class="spanMoney">￥</span>{{item.amount}}</div>
                                    </div>
                                </div>
                            </div>
                    </div>
                </div>
                <div class="note">
                    <div class="title">备注</div>
                    <van-field
                        v-model="note"
                        rows="2"
                        autosize
                        type="textarea"
                        maxlength="50"
                        placeholder="请输入您需要备注的信息"
                        show-word-limit
                    />
                </div>
            </div>
            <div class="divCart">
                <div :class="{imgCartActive: cartData && cartData.length > 0, imgCart:!cartData || cartData.length<1}"></div>
                <div :class="{divGoodsNum:1===1, moreGoods:cartData && cartData.length > 99}" v-if="cartData && cartData.length > 0">{{ goodsNum }}</div>
                <div class="divNum">
                    <span>￥</span>
                    <span>{{goodsPrice}}</span>
                </div>
                <div class="divPrice"></div>
                <div :class="{btnSubmitActive: cartData && cartData.length > 0, btnSubmit:!cartData || cartData.length<1}" @click="ORCode">去支付</div>
            </div>
            <!-- 微信支付二维码 -->
            <el-dialog
                :visible.sync="codeDialogVisible"
                :show-close="false"
                @close="closeDialog"
                width="230px"
                center>
                <div ref="qrcode"  style="width:200px; height:200px;"></div>
                    使用微信扫码支付
            </el-dialog>
        </div>
        <!-- 开发环境版本，包含了有帮助的命令行警告 -->
        <script src="../../backend/plugins/vue/vue.js"></script>
        <!-- 引入组件库 -->
        <script src="../../backend/plugins/element-ui/index.js"></script>
        <!-- 引入vant样式 -->
        <script src="../js/vant.min.js"></script>
        <script src="../api/address.js"></script>
        <!-- 引入axios -->
        <script src="../../backend/plugins/axios/axios.min.js"></script>
        <script src="../js/request.js"></script>
        <script src="../js/common.js"></script>
        <script src="../api/main.js"></script>
        <script src="../api/order.js"></script>
        <!--QRCode-->
        <script type="text/javascript" src="http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://static.runoob.com/assets/qrcode/qrcode.min.js"></script>
        <script type="module">
            new Vue({
                el:"#add_order",
                data(){
                    return {
                        address:{
                            phone:'',//手机号
                            consignee:'',//姓名
                            detail:'',//详细地址
                            sex:'1',
                            id:undefined
                        },
                        finishTime:'',//送达时间
                        cartData:[],
                        note:'',//备注信息
                        codeDialogVisible: false, //微信支付二维码弹窗
                        order_id:'',   //订单id
                        Code_url:'',  //支付二维码
                        qrcode: null,  //生成二维码
                        timer:null,   //定时器
                    }
                },
                computed:{
                    goodsNum(){
                        let num = 0
                        this.cartData.forEach(item=>{
                            num += item.number 
                        })
                        if(num <99){
                            return num
                        }else{
                            return '99+'
                        }
                    },
                    goodsPrice(){
                    let price = 0
                    this.cartData.forEach(item=>{
                        price += (item.number * item.amount)
                    })
                    return price
                    }
                },
                created(){
                    this.initData()
                },
                mounted(){},
                methods:{
                    goBack(){
                        history.go(-1)
                    },
                    initData(){
                        //获取默认的地址
                        this.defaultAddress()
                        //获取购物车的商品
                        this.getCartData()
                    },
                    //获取默认地址
                    async defaultAddress(){
                        const res = await  getDefaultAddressApi()
                        if(res.code === 1){
                           this.address = res.data
                           this.getFinishTime()
                        }else{
                            window.requestAnimationFrame(()=>{
                                window.location.href = '/front/page/address-edit.html'
                            })
                        }
                    },
                    //获取送达时间
                    getFinishTime(){
                        let now = new Date()
                        let hour = now.getHours() +1
                        let minute = now.getMinutes()
                        if(hour.toString().length <2){
                            hour = '0' + hour
                        }
                        if(minute.toString().length <2){
                            minute = '0' + minute
                        }
                        this.finishTime = hour + ':' + minute
                    },
                    toAddressPage(){
                        window.requestAnimationFrame(()=>{
                            window.location.href = '/front/page/address.html'
                        })
                    },
                    //获取购物车数据
                    async getCartData(){
                        const res = await cartListApi({})
                        if(res.code === 1){
                            this.cartData = res.data
                        }else{
                            this.$notify({ type:'warning', message:res.msg});
                        }
                    },
                    //提交订单
                    async goToPaySuccess(){
                        const params = {
                            remark:this.note,
                            payMethod:1,
                            addressBookId:this.address.id
                        }
                        const res = await addOrderApi(params)
                        if(res.code === 1){
                            window.requestAnimationFrame(()=>{
                                window.location.replace('/front/page/pay-success.html')
                            })
                        }else{
                            this.$notify({ type:'warning', message:res.msg});
                        }
                    },
                    //展示支付二维码
                    async ORCode(){
                        const params = {
                            remark:this.note,
                            payMethod:1,
                            addressBookId:this.address.id
                        }
                        console.log(params)
                        //发送异步请求
                        const res = await wxPay(params);
                        if(res.code === 1) {
                            console.log(res.data);
                            console.log(res.data.codeUrl);
                            if(res.data.message === "timeout") {
                                this.$notify({type:'warning',message:"订单已超时自动取消，请重新下单"});
                                //2秒后跳转页面
                                setTimeout(() => {
                                    window.requestAnimationFrame(()=>{
                                        window.location.replace('/front/index.html')
                                    })
                                }, 2000)
                                return;
                            }
                            this.Code_url = res.data.codeUrl;
                            this.order_id = res.data.orderId;
                            //打开二维码弹窗
                            this.codeDialogVisible = true
                            this.$nextTick(()=>{
                                if(this.qrcode != null){
                                    this.qrcode.clear(); // 清除代码
                                } else {
                                    this.qrcode = new QRCode(this.$refs.qrcode, {
                                        width : 180,
                                        height : 180,
                                        correctLevel:QRCode.CorrectLevel.L
                                    });
                                    //生成二维码
                                    this.qrcode.makeCode(this.Code_url);
                                }
                            });
                            //启动定时器
                            this.timer = setInterval(() => {
                                //查询订单是否支付成功
                                this.queryOrderStatus()
                            }, 3000)
                        } else {
                            this.$notify({type:'warning',message:res.msg});
                        }
                    },
                    //关闭微信支付二维码对话框
                    closeDialog(){
                        this.payBtnDisabled = false
                    },
                    //查询订单状态
                    async queryOrderStatus(){
                        const id= this.order_id;
                        //发送异步请求
                        const res = await getOrderStatus(id);
                        console.log("查询订单状态: " + res.code);
                        if(res.code === 1) {
                            console.log('清除定时器')
                            clearInterval(this.timer)
                            // 一秒后跳转到订单列表
                            setTimeout(() => {
                                window.requestAnimationFrame(()=>{
                                    window.location.replace('/front/page/pay-success.html')
                                })
                            }, 1000)
                        }
                    },
                    //网络图片路径转换
                    imgPathConvert(path){
                        return imgPath(path)
                    },
                }
            })
            </script>
        </body>
    </html>